<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    :width="640"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import {
    createDataProduct,
    updateDataProduct,
    fetchServiceData,
    type ServiceDataProduct,
    type CreateDataProductPayload,
    type UpdateDataProductPayload,
    type ServiceDataResource,
  } from '/@/api/service/dataSource';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n();
  const { showMessage } = useMessage();

  const isUpdate = ref(false);
  const recordData = ref<ServiceDataProduct | null>(null);
  const deviceId = ref<string>('');
  const resourceOptions = ref<{ label: string; value: string }[]>([]);

  const getTitle = computed(() => (unref(isUpdate) ? t('tb.dataProduct.modal.editTitle') : t('tb.dataProduct.modal.createTitle')));

  const formSchema: FormSchema[] = [
    {
      field: 'productName',
      label: t('tb.dataProduct.form.productName'),
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: t('tb.dataProduct.form.placeholders.productName'),
      },
    },
    {
      field: 'industry',
      label: t('tb.dataProduct.form.industry'),
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: t('tb.dataProduct.form.placeholders.industry'),
      },
    },
    {
      field: 'dataSize',
      label: t('tb.dataProduct.form.dataSize'),
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: t('tb.dataProduct.form.placeholders.dataSize'),
      },
    },
    {
      field: 'payMethod',
      label: t('tb.dataProduct.form.payMethod'),
      component: 'Select',
      required: true,
      componentProps: {
        placeholder: t('tb.dataProduct.form.placeholders.payMethod'),
        options: [
          { label: t('tb.dataProduct.payMethods.monthly'), value: '0' },
          { label: t('tb.dataProduct.payMethods.quarterly'), value: '1' },
          { label: t('tb.dataProduct.payMethods.yearly'), value: '2' },
        ],
      },
    },
    {
      field: 'dataSubject',
      label: t('tb.dataProduct.form.dataSubject'),
      component: 'Select',
      required: true,
      componentProps: {
        placeholder: t('tb.dataProduct.form.placeholders.dataSubject'),
        options: [
          { label: t('tb.dataProduct.types.individual'), value: '0' },
          { label: t('tb.dataProduct.types.enterprise'), value: '1' },
          { label: t('tb.dataProduct.types.public'), value: '2' },
        ],
      },
    },
    {
      field: 'providerName',
      label: t('tb.dataProduct.form.providerName'),
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: t('tb.dataProduct.form.placeholders.providerName'),
      },
    },
    {
      field: 'identityId',
      label: t('tb.dataProduct.form.identityId'),
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: t('tb.dataProduct.form.placeholders.identityId'),
      },
    },
    {
      field: 'enabled',
      label: t('tb.dataProduct.form.enabled'),
      component: 'Switch',
      required: false,
      defaultValue: 1,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      field: 'resourceId',
      label: t('tb.dataProduct.form.resourceId'),
      component: 'Select',
      required: false,
      componentProps: ({ formModel }) => ({
        placeholder: t('tb.dataProduct.form.placeholders.resourceId'),
        mode: 'multiple',
        options: unref(resourceOptions),
      }),
    },
    {
      field: 'description',
      label: t('tb.dataProduct.form.description'),
      component: 'InputTextArea',
      required: false,
      componentProps: {
        placeholder: t('tb.dataProduct.form.placeholders.description'),
        rows: 3,
        maxlength: 200,
        showCount: true,
      },
    },
  ];

  const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });

    isUpdate.value = !!data?.isUpdate;
    deviceId.value = data?.deviceId || '';

    // 获取资源列表
    await fetchResourceOptions();

    if (unref(isUpdate) && data.record) {
      recordData.value = data.record;
      const record = data.record as ServiceDataProduct;

      setFieldsValue({
        productName: record.productName,
        industry: record.industry,
        dataSize: record.dataSize,
        description: record.description,
        dataSubject: String(record.dataSubject),
        providerName: record.providerName,
        identityId: record.identityId,
        payMethod: String(record.payMethod),
        resourceId: record.resourceId || [],
        enabled: record.enabled == 1 || record.enabled === '1' ? 1 : 0,
      });
    }
  });

  async function fetchResourceOptions() {
    try {
      const response = await fetchServiceData<ServiceDataResource>(deviceId.value, 'resource');
      if (response && response.data && Array.isArray(response.data)) {
        resourceOptions.value = response.data.map((item) => ({
          label: `${item.resource_name || item.resouce_name} (${item.data_source_id})`,
          value: item.data_source_id,
        }));
      } else {
        resourceOptions.value = [];
      }
    } catch (error: any) {
      console.error('获取资源列表失败:', error);
      resourceOptions.value = [];
    }
  }

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });

      const payload: any = {
        productName: values.productName,
        industry: values.industry,
        dataSize: values.dataSize,
        description: values.description || '',
        dataSubject: String(values.dataSubject),
        providerName: values.providerName,
        identityId: values.identityId,
        payMethod: String(values.payMethod),
        resourceId: values.resourceId || [],
        enabled: String(values.enabled),
      };

      if (unref(isUpdate) && recordData.value) {
        const updatePayload: UpdateDataProductPayload = {
          ...payload,
          '.name': recordData.value['.name'],
          '.index': recordData.value['.index'],
          __index: recordData.value.__index || recordData.value['.index'],
        };
        await updateDataProduct(deviceId.value, updatePayload);
        showMessage(t('tb.dataProduct.messages.updateSuccess'), 'success');
      } else {
        const createPayload: CreateDataProductPayload = payload;
        await createDataProduct(deviceId.value, createPayload);
        showMessage(t('tb.dataProduct.messages.createSuccess'), 'success');
      }

      closeModal();
      emit('success');
    } catch (error: any) {
      console.error('提交数据产品失败:', error);
      showMessage(error.message || t('tb.dataProduct.messages.submitError'), 'error');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleCancel() {
    closeModal();
  }
</script>
